//实现一个翻译服务器
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/InetAddress.h>
#include <muduo/net/Buffer.h>
#include <muduo/net/TcpConnection.h>
#include <iostream>
#include <unordered_map>

using namespace muduo;
using namespace muduo::net;

class DictServer {
public:
    DictServer(EventLoop* loop, const InetAddress& addr)
        : server_(loop, addr, "DictServer"),
          dict_{{"apple", "苹果"}, {"banana", "香蕉"}, {"orange", "橘子"}} {
        server_.setConnectionCallback(
            std::bind(&DictServer::onConnection, this, _1));
        server_.setMessageCallback(
            std::bind(&DictServer::onMessage, this, _1, _2, _3));
    }

    void start() {
        server_.start();
    }

private:
    void onConnection(const TcpConnectionPtr& conn) {
        if (conn->connected()) {
            std::cout << "连接建立" << std::endl;
        } else {
            std::cout << "连接断开" << std::endl;
        }
    }

    void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp) {
        std::string msg = buf->retrieveAllAsString();
        msg.pop_back(); // 去掉 \n
        auto it = dict_.find(msg);
        if (it != dict_.end()) {
            conn->send(it->second + "\n");
        } else {
            conn->send("没有找到对应的翻译\n");
        }
    }

    TcpServer server_;
    std::unordered_map<std::string, std::string> dict_;
};

int main() {
    EventLoop loop;
    InetAddress addr(8080);
    DictServer server(&loop, addr);
    server.start();
    std::cout << "DictServer running on 8080..." << std::endl;
    loop.loop();
    return 0;
}